<template>
  <div class="app-container">
    <!-- 对象搜索 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="字典名称" prop="type">
        <y-select v-model="queryParams.type" placeholder="请选择字典名称" :options="typeOptions" />
      </el-form-item>
      <el-form-item label="数据标签" prop="label">
        <el-input v-model="queryParams.label" placeholder="请输入数据标签" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <y-select v-model="queryParams.status" placeholder="请选择数据状态" :options="sys_enable_disable" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 对象操作 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Back" @click="handleBack">返回</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['sys:dict:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['sys:dict:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['sys:dict:delete']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <y-export :url="'sys/dict/data/export/'" :ids="ids" :filename="'dict_data'" v-hasPermi="['sys:dict:export']" />
      </el-col>
      <y-right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns" />
    </el-row>

    <!-- 对象列表 -->
    <el-table ref="tableRef" v-loading="loading" row-key="id" :data="dataList"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" reserve-selection />
      <el-table-column label="序号" width="100" align="center" type="index">
        <template #default="scope">
          {{ scope.$index + (queryParams.page - 1) * queryParams.limit + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="编号" align="center" prop="id" v-if="columns[0].visible" />
      <el-table-column label="数据标签" align="center" prop="label" v-if="columns[1].visible">
        <template #default="scope">
          <span v-if="(scope.row.tagType == '' || scope.row.tagType == 'default') &&
      (scope.row.tagClass == '' || scope.row.tagClass == null)
      ">{{ scope.row.label }}</span>
          <el-tag v-else :type="scope.row.tagType" :class="scope.row.tagClass">{{ scope.row.label }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="数据键值" align="center" prop="value" v-if="columns[2].visible" />
      <el-table-column label="显示排序" align="center" prop="sort" v-if="columns[3].visible" />
      <el-table-column label="状态" align="center" prop="status" v-if="columns[4].visible">
        <template #default="scope">
          <y-dict-tag :options="sys_enable_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true"
        v-if="columns[5].visible" />
      <el-table-column label="创建时间" align="center" prop="create_time" width="180" v-if="columns[6].visible">
        <template #default="scope">
          <span>{{ parseTime(scope.row.create_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" with="100" align="center">
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['sys:dict:edit']" />
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
              v-hasPermi="['sys:dict:delete']" />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <y-pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.limit"
      @pagination="getList" />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="dataRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="字典类型">
          <el-input v-model="form.type" :disabled="true" />
        </el-form-item>
        <el-form-item label="数据标签" prop="label">
          <el-input v-model="form.label" placeholder="请输入数据标签" />
        </el-form-item>
        <el-form-item label="数据键值" prop="value">
          <el-input v-model="form.value" placeholder="请输入数据键值" />
        </el-form-item>
        <el-form-item label="样式属性" prop="tagClass">
          <el-input v-model="form.tagClass" placeholder="请输入样式属性" />
        </el-form-item>
        <el-form-item label="显示排序" prop="sort">
          <el-input-number v-model="form.sort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="回显样式" prop="tagType">
          <el-select v-model="form.tagType">
            <el-option v-for="item in listClassOptions" :key="item.value" :label="item.label + '(' + item.value + ')'"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in sys_enable_disable" :key="dict.value" :value="dict.value">{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="5" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Data">
import useDictStore from "@/store/modules/dict";
import { listType, getType } from "@/api/sys/dict/type";
import {
  listData,
  getData,
  delData,
  addData,
  updateData,
} from "@/api/sys/dict/data";

const { proxy } = getCurrentInstance();
const { sys_enable_disable } = proxy.useDict("sys_enable_disable");

const dataList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(false);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const defaultDictType = ref("");
const typeOptions = ref([]);
const route = useRoute();

// 列显隐信息
const columns = ref([
  { key: 0, label: `编号`, visible: false },
  { key: 1, label: `数据标签`, visible: true },
  { key: 2, label: `数据键值`, visible: true },
  { key: 3, label: `显示排序`, visible: true },
  { key: 4, label: `状态`, visible: true },
  { key: 5, label: `备注`, visible: false },
  { key: 6, label: `创建时间`, visible: true },
]);

// 数据标签回显样式
const listClassOptions = ref([
  { value: "default", label: "默认" },
  { value: "primary", label: "主要" },
  { value: "success", label: "成功" },
  { value: "info", label: "信息" },
  { value: "warning", label: "警告" },
  { value: "danger", label: "危险" },
]);

const data = reactive({
  form: {},
  queryParams: {
    type: undefined,
    label: undefined,
    status: undefined,
    page: 1,
    limit: 10,
  },
  rules: {
    label: [{ required: true, message: "数据标签不能为空", trigger: "blur" }],
    value: [{ required: true, message: "数据键值不能为空", trigger: "blur" }],
    sort: [{ required: true, message: "数据顺序不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询字典类型详细 */
function getTypes(id) {
  getType(id).then((response) => {
    queryParams.value.type = response.data.type;
    defaultDictType.value = response.data.type;
    getList();
  });
}

/** 查询字典类型列表 */
function getTypeList() {
  listType().then((response) => {
    typeOptions.value = response.data;
  });
}

/** 查询字典数据列表 */
function getList() {
  loading.value = true;
  listData(queryParams.value).then((response) => {
    dataList.value = response.data;
    total.value = response.total;
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    label: undefined,
    value: undefined,
    tagClass: undefined,
    tagType: "default",
    sort: 0,
    status: "0",
    remark: undefined,
  };
  proxy.resetForm("dataRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.page = 1;
  getList();
}

/** 返回按钮操作 */
function handleBack() {
  proxy.$router.back();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.type = defaultDictType.value;
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加字典数据";
  form.value.type = queryParams.value.type;
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value;
  getData(id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改字典数据";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["dataRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != undefined) {
        updateData(form.value).then((response) => {
          useDictStore().removeDict(queryParams.value.type);
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addData(form.value).then((response) => {
          useDictStore().removeDict(queryParams.value.type);
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
async function handleDelete(row) {
  try {
    if (row.id) {
      await proxy.$modal.confirm(`确认是否删除 "${row.name}" ？`);
    }
    else {
      await proxy.$modal.confirm("确认是否删除所有已勾选信息？");
    }
    ids.value = row.id ? [row.id] : ids.value;
    await delData(ids.value);
    proxy.$modal.msgSuccess("删除成功");
    proxy.$refs.tableRef.clearSelection()
    getTypes(route.params && route.params.id);
    getTypeList();
  } catch (error) {
    console.error(error);
  }
}

onMounted(() => {
  getTypes(route.params && route.params.id);
  getTypeList();
})
</script>
